<template>
    <view class="page-wrap">
        <view class="create">
            <u-form :model="form" ref="uForm" label-width="6em">
                <u-form-item borderBottom label="学校" prop="schoolId" @click="toSchool">
                    <u-input disabled placeholder="请选择学校" v-model="form.schoolName" />
                    <u-icon slot="right" name="arrow-right" />
                </u-form-item>
                <u-form-item borderBottom label="取件点" prop="stationName" @click="stationShow = !disabled">
                    <u-input placeholder="请选择取件点" v-model="form.stationName" disabled />
                    <u-picker :show="stationShow" :columns="stationList" @confirm="handleStation" key-name="name"
                        @cancel="stationShow = false" />
                    <u-icon slot="right" name="arrow-right" />
                </u-form-item>
                <u-form-item borderBottom label="收货地址" prop="dormitoryId" @click="toDormitory">
                    <u-input placeholder="请选择收货地址" :value="address" disabled />
                    <u-icon slot="right" name="arrow-right" />
                </u-form-item>
                <u-form-item borderBottom label="包裹规格" prop="orderExpresses" label-position="top">
                    <view class="express" v-for="exp in form.orderExpresses" :key="exp.priceId">
                        <view class="express-title">{{exp.title}}<text>￥{{exp.price}}</text></view>
                        <view class="express-count">
                            <u-number-box v-model="exp.count" :min="0" :max="99" :decimal-length="0"
                                button-size="50rpx" inputWidth="80rpx" :disabled="disabled" />
                        </view>
                    </view>
                    <text class="helper">{{appConfig.xypsExpressHelper}}</text>
                </u-form-item>
                <u-form-item borderBottom label="取件码" prop="expressCodes" label-position="top">
                    <u-textarea border="none" auto-height v-model="form.expressCodes" placeholder="请输入取件码,多个请逗号分隔"
                        @blur="handleExpressCodes" :disabled="disabled" />
                    <view class="helper">多个请取件码逗号分隔</view>
                    <view class="helper">不同的取件点的包裹请分开下单</view>
                    <view class="helper">无取件码请填写快递物流单号，并附上截图</view>
                </u-form-item>
                <u-form-item borderBottom label="备注(选填)" prop="memberRemark">
                    <u-input placeholder="请输入备注" v-model="form.memberRemark" :disabled="disabled" />
                </u-form-item>
                <u-form-item borderBottom label="截图(选填)" prop="" label-position="top">
                    <tui-upload width="195" height="195" :server-url="uploadUrl" :header="uploadHead"
                        style="margin-top: 16rpx" :sizeType="['compressed']" :forbid-add="disabled"
                        @complete="handleUploadComplete"></tui-upload>
                </u-form-item>
                <u-form-item borderBottom label="优惠券" prop="coupons" @click="couponShow = !disabled">
                    <u-input :placeholder="disabled? '无' : '请选择优惠券'" :value="payCouponAmount" disabled />
                    <CouponModuleUsable :show="couponShow" :max="totalAmount" :order-id="form.id" :def="form.coupons"
                        @close="couponShow = false" @confirm="handleCoupon" />
                    <u-icon slot="right" name="arrow-right" />
                </u-form-item>
            </u-form>
        </view>
        <footer-wrap>
            <view class="footer">
                <view v-if="disabled && form.payStatus == 'WAIT'" class="amount pay-cancel" @click="handleCancel">
                    取消订单
                </view>
                <view v-else class="amount">
                    <view>
                        合计：
                        <text class="pay-amount" v-if="disabled">￥{{form.payAmount}}</text>
                        <text class="pay-amount" v-else>￥{{(totalAmount - couponAmount).toFixed(2)}}</text>
                    </view>
                    <view class="coupon" v-if="payCouponAmount">
                        已减：<text>￥{{payCouponAmount}}</text>
                    </view>
                </view>
                <view class="action">
                    <u-button v-if="disabled && form.payStatus == 'WAIT'" shape="circle"
                        type="primary" size="large" @click="handlePay">继续支付 ￥{{form.payAmount}}</u-button>
                    <u-button v-else-if="!disabled" shape="circle" type="primary" size="large"
                        @click="handleSave">立即支付</u-button>
                    <view v-else class="pay-status">
                        <text class="cancel" v-if="form.payStatus == 'CANCELED'">{{form.payStatusName}}</text>
                        <text v-else-if="form.deliveryStatus == 'FINISH'" class="finish">{{form.deliveryStatusName}}</text>
                        <text v-else-if="form.deliveryStatus">{{form.deliveryStatusName}}</text>
                        <text v-else>{{form.payStatusName}}</text>
                    </view>
                </view>
            </view>
        </footer-wrap>
    </view>
</template>

<script>
    import {
        mapState
    } from 'vuex';
    import CouponModuleUsable from '@/pages/coupon/moduleUsable.vue'
    export default {
        components: {
            CouponModuleUsable
        },
        data() {
            return {
                list: [],
                option: {
                    size: 15, // 分页大小
                    auto: true // 自动加载列表
                },
                stationShow: false,
                stationList: [
                    []
                ],
                couponShow: false,
                couponAmount: 0,
                form: {
                    id: '',
                    stationId: '',
                    stationName: '',
                    dormitoryId: '',
                    schoolId: '',
                    schoolName: '',
                    buildingId: '',
                    buildingName: '',
                    address: '',
                    orderExpresses: [],
                    orderPictures: [],
                    expressCodes: '',
                    coupons: [],
                    totalAmount: '',
                    payAmount: '',
                    payStatus: '',
                    payStatusName: '',
                    deliveryStatus: '',
                    deliveryStatusName: '',
                }
            };
        },
        computed: {
            ...mapState(['school', 'appConfig']),
            address() {
                if (!this.form.dormitoryId) {
                    return;
                }

                return this.form.buildingName + ' ' + this.form.address;
            },
            totalAmount() {
                let amount = 0;
                this.form.orderExpresses.forEach(exp => {
                    amount += exp.price * exp.count;
                })
                return amount.toFixed(2);
            },
            disabled() {
                return this.form.payStatus;
            },
            uploadHead() {
                return {
                    token: this.token
                }
            },
            payCouponAmount() {
                let amount
                if (this.disabled) {
                    amount = this.form.totalAmount - this.form.payAmount;
                } else {
                    amount = this.couponAmount;
                }
                return amount || '';
            }
        },
        methods: {
            toSchool() {
                if (this.disabled) {
                    return;
                }
                this.$toPage({
                    url: '/pages/main/school',
                    params: {
                        event: 'orderSchoolChange'
                    }
                });
            },
            handleSchool(info) {
                if (!info) return;
                this.form.schoolId = info.id;
                this.form.schoolName = info.label;
                this.$api.station.list({
                    schoolId: info.id
                }).then(res => {
                    this.stationList = [res.list];
                })
                this.$api.dormitory.def({
                    schoolId: info.id
                }).then(res => {
                    this.handleDormitoryChange(res.info)
                })
            },
            handleStation(e) {
                console.log('handleStation', arguments)
                this.form.stationId = e.value[0].id;
                this.form.stationName = e.value[0].name;
                this.stationShow = false;
            },
            toDormitory() {
                if (this.disabled) {
                    return;
                }
                if (!this.form.schoolId) {
                    uni.showModal({
                        title: '提示',
                        content: '请选择学校',
                        showCancel: false,
                        success: () => {}
                    });
                    return;
                }
                this.$toPage({
                    url: '/pages/dormitory/list',
                    params: {
                        schoolId: this.form.schoolId,
                        event: 'dormitoryChange'
                    }
                });
            },
            handleDormitoryChange(info) {
                if (!info) return;
                this.form.dormitoryId = info.id;
                this.form.schoolId = info.schoolId;
                this.form.schoolName = info.schoolName;
                this.form.buildingId = info.buildingId;
                this.form.buildingName = info.buildingName;
                this.form.address = info.address;
            },
            handleExpressCodes(val) {
                console.log('handleExpressCodes', arguments)
                this.form.expressCodes = this.form.expressCodes.replace(/\s/g, '')
                    .replace(/[，,]+/g, ',')
                    .replace(/^[\s,]*/g, '')
                    .replace(/[\s,]*$/g, '')
            },
            handleUploadComplete({
                imgArr
            }) {
                console.log('handleUploadComplete', arguments)
                this.form.orderPictures = imgArr.map(img => {
                    return {
                        url: img
                    }
                })
            },
            handleCoupon(list, couponAmount) {
                console.log('handleCoupon', arguments)
                this.couponShow = false;
                this.couponAmount = couponAmount;
                this.form.coupons = list;
            },
            handleSave() {
                uni.showModal({
                    title: '提示',
                    content: '确定提交吗？',
                    success: (res) => {
                        if (!res.confirm) {
                            return;
                        }
                        console.log('save order', this.form)
                        this.$api.order.createOrder({
                            ...this.form
                        }).then(res => {
                            this.form.id = res.info;
                            this.handlePay();
                        })
                    }
                });
            },
            handlePay() {
                let id = this.form.id
                this.$api.order.wechatPay({
                    id
                }).then(res => {
                    if (res.payed) {
                        this.handleRefresh(id);
                        return;
                    }
                    uni.getProvider({
                        service: 'payment',
                        success: ({
                            service,
                            provider
                        }) => {
                            console.log('getProvider', arguments);
                            uni.requestPayment({
                                provider: provider[0],
                                ...res.params,
                                success: res => {
                                    this.handleRefresh(id);
                                },
                                fail: err => {
                                    console.log('支付失败', err)
                                    uni.showModal({
                                        title: '支付失败',
                                        showCancel: false,
                                        complete: () => {
                                            this.$toPage({
                                                type: 'redirect',
                                                url: '/pages/main/add?id=' + id
                                            });
                                        }
                                    })
                                }
                            });
                        }
                    });
                });
            },
            handleRefresh(orderId) {
                this.$api.order.refresh({
                    orderId
                }).then(res => {
                    if (res.success) {
                        uni.showToast({
                            title: '支付成功!'
                        });
                    } else {
                        uni.showToast({
                            title: '支付完成!'
                        });
                    }
                    setTimeout(() => {
                        this.$toPage({
                            type: 'back'
                        });
                    }, 2000);
                })
            },
            handleCancel() {
                uni.showModal({
                    title: '提示',
                    content: '确定要取消该订单吗？',
                    success: (res) => {
                        if (!res.confirm) {
                            return;
                        }
                        this.$api.order.cancel({
                            orderId: this.form.id
                        }).then(res => {
                            uni.showModal({
                                title: '订单取消成功',
                                showCancel: false,
                                complete: () => {
                                    this.$toPage({
                                        type: 'back'
                                    });
                                }
                            })
                        });
                    }
                });
            },
        },
        watch: {
            'form.expressCodes'(val = '') {
                console.log('watch handleCodes', arguments)
                this.form.expressCodes = val.replace(/\s/g, '').replace(/[，,]+/g, ',')
            },
            'form.orderExpresses': {
                deep: true,
                handler() {
                    this.form.coupons = [];
                    this.couponAmount = 0;
                }
            }
        },
        onLoad(option) {
            if (option.id) {
                this.$api.order.info({
                    orderId: option.id
                }).then(res => {
                    Object.entries(res.info).forEach(([key, val]) => {
                        if (this.form[key] !== undefined) {
                            this.form[key] = val;
                        }
                    });
                    this.$nextTick(() => {
                        this.form.coupons = res.info.coupons || [];
                    })
                })
            } else {
                uni.$on('orderSchoolChange', info => {
                    console.log('orderSchoolChange：', info);
                    this.handleSchool(info);
                })
                uni.$on('dormitoryChange', info => {
                    console.log('监听到事件来自返回的参数：', arguments);
                    // TODO 下面执行刷新的方法
                    this.handleDormitoryChange(info)
                })
                this.school && this.handleSchool(this.school)
                this.$api.order.prices().then(res => {
                    res.priceList.forEach(price => {
                        this.form.orderExpresses.push({
                            priceId: price.id,
                            title: price.title,
                            price: price.price,
                            count: 0,
                        })
                    })
                })
            }
        },
        onShow() {},
        onHide() {},
        onUnload() {},
        onReachBottom() {},
        onPageScroll(event) {},
        onPullDownRefresh() {},
        onShareAppMessage(options) {}
    };
</script>

<style scoped lang="scss">
    .page-wrap {
        min-height: 100vh;

        .box-title {
            margin: 32rpx;
            color: #333;

            text {
                color: $primary-color;
            }
        }

        .create {
            padding: 32rpx;
            margin-bottom: 180rpx;
            background-color: #fff;

            .express {
                text-align: right;
                line-height: 2em;

                .express-title {
                    display: inline-block;
                    padding-right: 1em;

                    text {
                        color: #F44336;
                    }
                }

                .express-count {
                    display: inline-block;
                }
            }

            .helper {
                color: $warning-color;
                font-size: 0.9em;
            }
        }

        .footer {
            display: flex;
            align-items: center;
            padding: 32rpx;

            .amount {
                flex-grow: 1;

                .pay-amount {
                    font-size: 1.5em;
                    color: #F44336;
                }

                .coupon {
                    font-size: 0.7em;

                    text {
                        color: #F44336;
                    }
                }
            }

            .action {
                width: 300rpx;

                .pay-status {
                    color: $primary-color;
                    font-size: 38rpx;
                    text-align: right;
                    
                    .finish {
                        color: $success-color;
                    }
                    
                    .cancel {
                        color: $warning-color;
                    }
                }
            }

            .pay-cancel+.action {
                width: 500rpx;
            }
        }
    }
</style>